﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;

namespace CheckWindowsServices
{
    public partial class CheckWSService : ServiceBase
    {
        private string configFilePath;
        private System.Timers.Timer timer;

        public CheckWSService()
        {
            InitializeComponent();
        }

        /*
　　        Windows服务在系统安装后会在注册表的 "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\[ServiceName]"下以服务的ServiceName建1个目录，目录中会有"ImagePath"节，这里保存的就是该服务的安装路径。
        */
        /// <summary>
        /// 获取服务安装路径
        /// </summary>
        /// <param name="ServiceName"></param>
        /// <returns></returns>
        public static string GetWindowsServiceInstallPath(string ServiceName)
        {
            string key = @"SYSTEM\CurrentControlSet\Services\" + ServiceName;
            string path = Registry.LocalMachine.OpenSubKey(key).GetValue("ImagePath").ToString();
            //替换掉双引号   
            path = path.Replace("\"", string.Empty);
            FileInfo fi = new FileInfo(path);
            return fi.Directory.ToString();
        }

        protected override void OnStart(string[] args)
        {
            if (args == null || args.Length < 1)
            {
                configFilePath = GetWindowsServiceInstallPath("CheckWindowsServices") + "\\check.conf";
            }
            else
            {
                string tmp = args[0];
                if (tmp.IndexOf("://") > 0)
                {
                    configFilePath = tmp;
                }
                else
                {
                    configFilePath = GetWindowsServiceInstallPath("CheckWindowsServices") + "\\" + tmp;
                }
            }

            timer = new System.Timers.Timer(1000 * int.Parse(ConfigurationManager.AppSettings["timespan"]));
            timer.Elapsed += timer_Elapsed;
            timer.Enabled = true;
            timer.Start();
        }

        private void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            using (StreamReader sr = new StreamReader(new FileStream(configFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
            {
                string line = sr.ReadLine();
                while (line != null)
                {
                    string[] args = line.Split(new char[] { ',', '，' });
                    if (args.Length > 0)
                    {
                        foreach (string item in args)
                        {
                            if (!string.IsNullOrEmpty(item))
                            {
                                if (!IsRunning(item))
                                {
                                    StartService(item);
                                }
                            }
                        }                        
                    }

                    line = sr.ReadLine();
                }
            }
        }

        protected override void OnStop()
        {
        }

        /// <summary>  
        /// 判断是否安装了某个服务  
        /// </summary>  
        /// <param name="serviceName"></param>  
        /// <returns></returns>  
        public static bool IsWindowsServiceInstalled(string serviceName)
        {
            try
            {
                ServiceController[] services = ServiceController.GetServices();

                foreach (ServiceController service in services)
                {
                    if (service.ServiceName == serviceName)
                    {
                        return true;
                    }
                }

                return false;
            }
            catch
            { return false; }
        }

        /// <summary>  
        /// 启动某个服务  
        /// </summary>  
        /// <param name="serviceName"></param>  
        public static void StartService(string serviceName)
        {
            try
            {
                ServiceController[] services = ServiceController.GetServices();

                foreach (ServiceController service in services)
                {
                    if (service.ServiceName == serviceName)
                    {
                        service.Start();

                        service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 30));
                    }
                }
            }
            catch { }
        }

        /// <summary>  
        /// 停止某个服务  
        /// </summary>  
        /// <param name="serviceName"></param>  
        public static void StopService(string serviceName)
        {
            try
            {
                ServiceController[] services = ServiceController.GetServices();

                foreach (ServiceController service in services)
                {
                    if (service.ServiceName == serviceName)
                    {
                        service.Stop();

                        service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 30));
                    }
                }
            }
            catch { }
        }

        /// <summary>  
        /// 判断某个服务是否启动  
        /// </summary>  
        /// <param name="serviceName"></param>  
        public static bool IsStart(string serviceName)
        {
            bool result = true;

            try
            {
                ServiceController[] services = ServiceController.GetServices();

                foreach (ServiceController service in services)
                {
                    if (service.ServiceName == serviceName)
                    {
                        if ((service.Status == ServiceControllerStatus.Stopped)
                            || (service.Status == ServiceControllerStatus.StopPending))
                        {
                            result = false;
                        }
                    }
                }
            }
            catch { }

            return result;
        }

        /// <summary>  
        /// 判断某个服务是否启动  
        /// </summary>  
        /// <param name="serviceName"></param>  
        public static bool IsRunning(string serviceName)
        {
            bool result = false;

            try
            {
                ServiceController[] services = ServiceController.GetServices();

                foreach (ServiceController service in services)
                {
                    if (service.ServiceName == serviceName)
                    {
                        if (service.Status != ServiceControllerStatus.Running)
                        {
                            result = true;
                        }
                    }
                }
            }
            catch { }

            return result;
        }
    }
}
